<?php
$this->useClass("Action_Community_FeedHandler");
class Action_Community_ShowFeed extends Action_Community_FeedHandler
{
	public function getFeedModel() {
		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
		$this->rh->UseClass("AggregatedModel_Feed_ReaderItems");

		return new AggregatedModel_Feed_ReaderItems();
	}

	var $ajax_functions = array(
		'ajax_getSomePosts'
		);

	public function ajax_getSomePosts( $page_number ) {

		$this->setParam("page_number", $page_number);

		$this->model->doStuff();

		$view = $this->rh->views->findByName('items');
		$view->data = $this->aa->template_data;
		$items = $this->model->getItems();

		if ($items) {
			$view->data['items'] = $this->processItems($items);
		}

		$items_node = $this->rh->ctx->cp->add_node("items");
		// важный флажок для отрисовки заголвка итема
		$this->renderCurrentTdi($view);

		$items_node->set_data( $view->getContent() ); // рендеринг итемов

		$this->addPagerNodes ($this->rh->ctx->cp);
	}

	protected function init() {
		parent::init();
		$this->m_tdi = $this->ctx->mm->getModel("Tdi", "m");

		$tdi_oids = array();
		foreach ($this->aa->acl_data['tdi_list'] as $tdi) $tdi_oids[] = $tdi['id_object'];
		$this->sections = $this->m_tdi->getSections($tdi_oids);

		$this->rh->UseClass("RL_URLGenerator");

	}

	public function getWidgetsConfig ()
	{
		$widgets = array();

		$widgets[] = array (
			'name' => 'CreateBtnWidget',
			'params' => array(
				'widget_position' => 'createbtn',
				'widget_view' => 'WG_CreateBtnWidget',
			),
		);

		$widgets[] = array (
			'name' => 'Feed_DoctypesMenuWidget',
			'params' => array(
				'widget_position' => 'tags',
				'widget_view' => 'WG_Feed_DoctypesMenuWidget',
			),
		);

		$widgets[] = array (
			'name' => 'TagsWidget',
			'params' => array(
				'community_oid' => $this->aa->acl_data['comity_oid'],
				'tdi_oid'=> $this->aa->acl_data['tdi_oid'],
				'tag' => $this->getParam('tag'),
				'widget_position' => 'tags',
				'widget_view' => 'WG_Feed_TagsWidget',
			),
		);
		$widgets[] = array(
				'name' => 'SectionsManageWidget',
				'params' => array(
					'widget_position' => 'community_settings_widgets',
					'widget_view' => 'WG_SectionsManage',
			));

		if (!isset($this->params['tdi_url'])) {
			$widgets[] = array(
				'name' => 'Feed_TdiMenuWidget',
				'params' => array(
					'community_oid' => $this->aa->acl_data['comity_oid'],
					'tdi_oid'=> $this->aa->acl_data['tdi_oid'],
					'widget_position' => 'tags',
					'widget_view' => 'WG_Feed_TdiMenuWidget',
				),
			);
		}

		$widgets[] = array (
			'name' => 'RssWidget',
			'params' => array(
				'widget_view' => 'WG_RssWidget',
				'widget_position' => 'tags',
			),
		);

		return $widgets;
	} // end of function getWidgetsConfig

	private function processItems($items) {
		foreach ($items as $i=>$item) {
			$items[ $i ]['section'] = $this->sections[ $item['post']['tdi_oid'] ];
			$items[ $i ]['acl'] = $this->aa->getAcl( $item['post']['oid'] );

			if ($item['post']['type'] == 'fvote') {
				// установить bool $item['voted'] если текущий пользователь голосовал
				$vm = $this->ctx->mm->getModel("Vote", "m");
				$aa = $this->aa;
				$items[ $i ]['already_voted'] = $vm->checkUserVote($item['post']['oid'], $aa->acl_data['user_id']);

				// создать ссылку на голосоватор за данный итем
				$ug = new RL_URLGenerator($this->rh->router->getRule("vote_manager")); //
				$ug->setRouter($this->rh->router);
				$ug->setParams(array(
					"community_url"=>$this->params['community_url'],
					"id_item"=>$item['post']['oid'],
					)
				);
				$items[ $i ]['vote_url'] = $ug->generateUrl();
				unset($ug);

				if ($item['post']['posted_by_id'] == $this->aa->acl_data['user_id']) {
					if ( $item['vote_closed'] ) {
						$items[$i]['can_open'] = 1;
					} else {
						$items[$i]['can_close'] = 1;
					}
				}

				$items[$i]['can_vote'] = (isset($this->aa->acl_data['user_id'])) ? true : false;
			}
		}
		return $items;
	}

	public function process ()
	{
		$aa = &$this->aa;
		if (!$aa->is_granted(array('item_read'))) {
			$this->rh->response->setContent( "access denied" );
			return false;
		}

		$aa->checkDeletions( array($this, "shutdown") );

		$this->model->doStuff();

		$view = $this->rh->views->findByName('feed');
		$view->data = $aa->template_data;

		$view->data['can_create'] = $aa->is_granted(array('item_create', 'item_create_premod'));

		$items = $this->model->getItems();

		/**
		 * если какой юзер правил топик, надо подтянуть его данные
		 */
		foreach ( $items as $key=>$val ) {
			if ( isset($val['post']['edited_user_oid']) && !empty($val['post']['edited_user_oid']) ) {
				$object = $this->ctx->store->getObject($val['post']['edited_user_oid']);
				$items[$key]['post']['edited_user'] = $object->data;
			}
		}

		if ($items) {
			// добавим к каждой записи информацию о разделе, пересчитаем права, рассчитаем URL адреса
			$view->data['items'] = $this->processItems($items);
		} else {
			$view->data['message'] = "В этой ленте нет сообщений.";
		}

		// данные для постраничной листалки
		$pager = $this->getPagerInfo();
		$view->data['page'] = $pager;
		$view->data['items_remaining'] = $pager['items_remaining'];


		$this->renderFilters($view);


		$view->data['__widgets__'] = $this->widgets;

		// генерация урл адресов
		$ug = new RL_URLGenerator($this->rh->router->getLastMatched()); //$this->rh->router->getRule('object_undelete')
		$ug->setRouter($this->rh->router);
		$ug->setParams($this->params);

		// урл для постраничной листалки без ajax
		if (isset($pager['prev'])) {
			$ug->setGet(array_merge($this->rh->GET, array("p"=>$pager['prev'])));
			$view->data["prev_url"] = $ug->generateUrl();
		}

		if (isset($pager['next'])) {
			$ug->setGet(array_merge($this->rh->GET, array("p"=>$pager['next'])));
			$view->data["next_url"] = $ug->generateUrl();
		}

		unset($ug);

		// для постраничной листалки ajax handler
		if ( isset($this->params['tdi_url']) ) {
			$ug = new RL_URLGenerator($this->rh->router->getRule('showfeed_tdi_ajax'));
		} else {
			$ug = new RL_URLGenerator($this->rh->router->getRule('showfeed_ajax'));
		}
		$ug->setRouter($this->rh->router);
		$ug->setParams($this->params);
		$ug->setGet($this->rh->GET);

		$view->data['ajax_url'] = $ug->generateUrl();

		$this->rh->response->setContent( $view );

		// -- touch visitor stat -- {{{
		// visit  tdi
		$this->ctx->mm->getModel("Visitable", "m")->getVisitable('Tdi')->visit();
		//
		// -- touch visitor stat -- }}}

	} // end of function process

}
